package com.zach.common.aop;

import java.lang.reflect.Method;
import java.util.Collection;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.dao.DataAccessException;

public class LogAop {
	private static Log log = LogFactory.getLog(LogAop.class.getName());
	public LogAop() {
	}

	public Object aroundLog(ProceedingJoinPoint pjp) throws Throwable {
		// start stopwatch
		log.info("around before "+pjp.getSignature().getName()+"()");
		log.info(JSONArray.fromObject(pjp.getArgs()));
		Object retVal = pjp.proceed();
		// stop stopwatch
		log.info("around after");
		return retVal;
	}
	
	
	public void simpleBeforeLog() {
		log.info("传统经典aop的before...");
	}
	public void beforeLog(JoinPoint joinPoint) {
		log.info(joinPoint.getTarget().getClass()+"."+joinPoint.getSignature().getName()+"()");
//		log.info("info target:"+joinPoint.getTarget().getClass());
		log.info("params:"+JSONArray.fromObject(joinPoint.getArgs()).toString());
	}

	/**
	 * <aop:after-returning pointcut-ref="dataAccessOperation"
	 * returning="retVal" method="doAccessCheck"/>
	 * 
	 * @param retVal
	 */
	public void afterReturnLog(JoinPoint jp,Object retVal) {
		if(null!=retVal){
			if(retVal instanceof Collection){
				log.info(jp.getSignature().getName()+"() ==>"+JSONArray.fromObject(retVal).toString());  
			}else{
				log.info(jp.getSignature().getName()+"() ==>"+JSONObject.fromObject(retVal).toString());  
			}
		}else{
			log.info(jp.getSignature().getName()+"() ==> null");
		}
	}

	/**
	 * <aop:after-throwing pointcut-ref="dataAccessOperation"
	 * throwing="dataAccessEx" method="doRecoveryActions"/>
	 */
	public void afterThrowing(DataAccessException dataAccessEx) {
		System.out.println("传统经典aop的afterThrowing...");
	}

	public void afterThrowing(Method method, Object[] args, Object target,
			Throwable throwable) {
		System.out.println("传统经典aop的afterThrowing2...");
	}
}
